import {PureComponent} from "react";
import store from "../store";

export default function connect(mapStateToProps,mapDispatchToProps){

    // 高阶组件，， 接收一个component
    return function (WrapperComponent){
        // mapStateToProps()


        class NewComponent extends PureComponent{


            constructor(props) {
                super(props);
                this.state = store.getState()
            }

            componentDidMount() {
               this.unsubscribe =  store.subscribe(()=>{
                    // setState会做浅层比较，，，性能优化
                    this.setState(store.getState())
                })
            }
            componentWillUnmount() {
                this.unsubscribe()
            }

            // componentDidMount() {
            //     store.subscribe(()=>{
            //         // 强制执行render
            //         this.forceUpdate()
            //     })
            // }

            render() {
                // 只会渲染第一次，，， 他不知道store是否改变
                const stateObj = mapStateToProps(store.getState())
                var dispatchObj = mapDispatchToProps(store.dispatch);
                return <WrapperComponent {...this.props} {...stateObj} {...dispatchObj}></WrapperComponent>
            }
        }


        return NewComponent
    }



}
